﻿@using Xms.Schema.Extensions;

@model Xms.Web.Models.EntityGridModel
@{
    Layout = null;
}
@{
    var mainEntity = Model.EntityList.First();
    var gridid = "queryview-section-" + Guid.NewGuid().ToString("N");
}
@{
    var jsLibs = new List<string>();
    var resources = new List<Guid>();
    if (Model.IsShowButtons && Model.RibbonButtons.NotEmpty())
    {
        foreach (var btn in Model.RibbonButtons)
        {
            if (btn.JsLibrary.IsNotEmpty())
            {
                if (btn.JsLibrary.StartsWith("$webresource:"))
                {
                    var wsId = Guid.Parse(btn.JsLibrary.Replace("$webresource:", ""));
                    if (!resources.Contains(wsId))
                    {
                        resources.Add(wsId);
                    }
                }
                else if (!jsLibs.Contains(btn.JsLibrary))
                {
                    jsLibs.Add(btn.JsLibrary);
                }
            }
        }
    }
}

<div id="@gridid" class="grid" style="border: 1px solid #eee;">
    <input type="hidden" name="allsubgirddata" value="" />
    <input type="hidden" name="tempdata" value="" />
    <input type="hidden" name="resdata" value="" />
    <div class="container-fluid" style="padding:3px;">
        <div class="toolbar">
            <div class="pull-left" style="line-height:35px;">
                @if (Model.IsEditable)
                {
                    <button type="button" class="btn btn-link btn-xs" name="createBtn" title="@app.T["window_opennew"]">
                        <span class="glyphicon glyphicon-plus-sign"></span> @app.T["new"]
                    </button>
                    <button type="button" class="btn btn-link btn-xs" name="deleteBtn"><span class="glyphicon glyphicon-trash"></span> @app.T["delete"]</button>
                    <button type="button" class="btn btn-link btn-xs" name="freshBtn"><span class="glyphicon glyphicon-refresh"></span> @app.T["refresh"]</button>
                    <button type="button" class="btn btn-link btn-xs btnLocal" name="addRowBtnLocal"><span class="glyphicon glyphicon-plus"></span> 插入行</button>
                    <button type="button" class="btn btn-link btn-xs " name="saveBtnLocal"><span class="glyphicon glyphicon-floppy-disk"></span>保存</button>
                }
                @if (Model.IsShowButtons && Model.RibbonButtons.NotEmpty())
                {
                    foreach (var btn in Model.RibbonButtons)
                    {
                        <a class="@btn.CssClass" href="javascript:void(0)" onclick="@btn.JsAction"><span class="@btn.Icon"></span> @btn.Label</a>
                    }
                }
            </div>
            <div class="pull-right">
                <table style="position:relative;">
                    <tr>
                        <td>
                            <div class="input-group input-group-sm col-sm-4">
                                @Html.TextBoxFor(x => x.Q, new { @class = "form-control quickly-search-input", @style = "width:200px;", @placeholder = app.T["search_quickly"] })
                                <span class="input-group-btn">
                                    <button class="btn btn-default" name="clearBtn" type="button" title="@app.T["clear"]">
                                        <span class="glyphicon glyphicon-remove-sign"></span>
                                    </button>
                                    <button class="btn btn-default" name="searchBtn" type="button">
                                        <span class="glyphicon glyphicon-search"></span>
                                    </button>
                                </span>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
    <div class="pos_re gridview" id="gridview">
        <div class="">
            <div class="table-responsive tableReWidth" id="tableReWidth" style="min-height:200px;max-height:300px;">
                <table class="table table-hover table-striped table-condensed datatable tableheaderResize" id="" data-pageurl="@app.Url" data-ajax="true" data-ajaxcontainer="gridview" data-sortby="@Model.SortBy.ToLower()" data-sortdirection="@Model.SortDirection" style="border-top: 1px solid lightgrey; max-width:none;">
                    <thead>
                        <tr>
                            @if (Model.IsEditable)
                            {
                                <th width="24" data-width="24" class="tableHeaderItem" style="width:24px;"><input type="checkbox" name="checkall" /></th>
                                <th width="30" data-width="30" style="width:30px;" class="tableHeaderItem"></th>
                            }
                            @{var theadW = 0;}
                            @if (Model.IsEditable && Model.RelationShipName.IsNotEmpty())// && Model.ReferencedRecordId.HasValue)
                            {
                                theadW += 80;
                                <th class="tableHeaderItem" data-width="40" style="width:40px;" data-operation="true"></th>
                            }
                            @{
                                int i = 0, count = Model.Grid.Rows[0].Cells.Count;
                                foreach (var cell in Model.Grid.Rows[0].Cells)
                                {
                                    var isrelated = cell.Name.IndexOf(".") > 0;
                                    var k = isrelated ? cell.Name.Split('.')[1] : cell.Name.ToLower();
                                    var label = cell.Label;
                                    theadW += cell.Width;
                                    Xms.Schema.Domain.Attribute attr = null;
                                    if (!isrelated)
                                    {
                                        attr = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && n.Name.IsCaseInsensitiveEqual(k));
                                        //label = attr.LocalizedName;
                                    }
                                    else
                                    {
                                        attr = Model.AttributeList.Find(n => n.EntityName.IsCaseInsensitiveEqual(cell.EntityName) && n.Name.IsCaseInsensitiveEqual(k));
                                        //显示字段+引用字段
                                        //var relationship = Model.RelationShipList.Find(n => n.Name.IsCaseInsensitiveEqual(cell.Name.Split('.')[0]));
                                        //label = attr.LocalizedName + "(" + relationship.ReferencingAttributeLocalizedName + ")";
                                    }
                                    if (attr == null) { continue; }
                                    var width = i == count - 1 ? "" : "width:" + cell.Width + "px";
                                    <th class="tableHeaderItem" data-width="@cell.Width" data-name="@cell.Name.ToLower()" style="@(width)" data-label="@label" data-type="@attr.AttributeTypeName">
                                    </th>
                                    i++;
                                }

                            }
                        </tr>
                        <input type="hidden" id="tableHeaderWidth" class="tableHeaderWidth" value="@theadW" />
                    </thead>
                    <tbody>
                        @if (Model.IsEditable && Model.RelationShipName.IsNotEmpty())// && Model.ReferencedRecordId.HasValue)
                        {
                            <tr class="editrow" style="display:none;">
                                <td></td>
                                <td class="row-num"></td>
                                <td>
                                    @*<button type="button" class="btn btn-link btn-xs" name="saveRowBtn"><span class="glyphicon glyphicon-saved"></span></button>*@
                                    <button type="button" class="btn btn-link btn-xs" name="removeRowBtnLocal"><span class="glyphicon glyphicon-minus-sign"></span></button>
                                    @*<button type="button" class="btn btn-link btn-xs" name="resetRowBtn" title="重置"><span class="glyphicon glyphicon-share-alt"></span></button>*@
                                    <input type="hidden" name="recordid" />
                                    <input type="hidden" name="rownumber" />
                                </td>
                                @foreach (var cell in Model.Grid.Rows[0].Cells)
                                {
                                    var isrelated = cell.Name.IndexOf(".") > 0;
                                    var k = isrelated ? cell.Name.Split('.')[1] : cell.Name.ToLower();
                                    var label = cell.Label;
                                    Xms.Schema.Domain.Attribute attr = null;
                                    if (!isrelated)
                                    {
                                        attr = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && n.Name.IsCaseInsensitiveEqual(k));
                                        //label = attr.LocalizedName;
                                    }
                                    else
                                    {
                                        attr = Model.AttributeList.Find(n => n.EntityName.IsCaseInsensitiveEqual(cell.EntityName) && n.Name.IsCaseInsensitiveEqual(k));
                                        //显示字段+引用字段
                                        //var relationship = Model.RelationShipList.Find(n => n.Name.IsCaseInsensitiveEqual(cell.Name.Split('.')[0]));
                                        //label = attr.LocalizedName + "(" + relationship.ReferencingAttributeLocalizedName + ")";
                                    }
                                    if (attr == null) { continue; }
                                    var inputName = (Model.RelationShipName.IfEmpty(attr.EntityName) + "_" + attr.Name).ToLower();
                                    var required = attr.IsRequired ? "required" : "";
                                    <td data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-isrequired="@required" data-entityname="@attr.EntityName" data-localizedname="@attr.LocalizedName">
                                        @{
                                            if (attr.TypeIsLookUp())
                                            {
                                                if (attr.Name.IsCaseInsensitiveEqual("createdby") || attr.Name.IsCaseInsensitiveEqual("modifiedby"))
                                                {
                                                    <input type="text" data-isrelated="@isrelated" class="form-control  @(isrelated ? "" : "lookup")  input-sm" name="@(inputName + "_text")" data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-value="" data-lookup="@attr.ReferencedEntityId" data-entityname="@attr.EntityName" value="@(!isrelated ? app.CurrentUser.UserName : "")" disabled />
                                                }
                                                else
                                                {
                                                    <input type="text" data-isrelated="@isrelated" class="form-control input-sm @(isrelated ? "" : "lookup") typeahead" name="@(inputName + "_text")" data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-value="" data-lookup="@attr.ReferencedEntityId" data-entityname="@attr.EntityName" @(isrelated ? "disabled" : "") />
                                                    <input type="hidden" name="@(inputName)" data-isedit="true" data-name="@attr.Name.ToLower()" data-type="lookup" data-controltype="lookup" data-value="" data-lookup="@attr.ReferencedEntityId" data-entityname="@attr.EntityName">
                                                }
                                            }
                                            else if (attr.TypeIsDateTime())
                                            {
                                                <input type="text" data-isrelated="@isrelated" class="form-control  input-sm datepicker datetime" data-isedit="true" name="@(inputName)" data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-entityname="@attr.EntityName" data-format="@attr.DataFormat" data-dataformat="@attr.DataFormat" value="@(!isrelated && (attr.Name.IsCaseInsensitiveEqual("createdon") || attr.Name.IsCaseInsensitiveEqual("modifiedon")) ? DateTime.Now.ToString("yyyy-MM-dd") : "")" @(isrelated || attr.Name.IsCaseInsensitiveEqual("createdon") || attr.Name.IsCaseInsensitiveEqual("modifiedon") ? " disabled" : "") />
                                            }
                                            @*else if (attr.TypeIsCustomer())
                                                {
                                                    <input type="text" class="form-control input-sm  @(isrelated ? "" : "lookup")  owner" data-isedit="true" name="@(inputName + "_text")" data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-lookup="@attr.ReferencedEntityId" data-entityname="@attr.EntityName" value="@(!isrelated ? app.CurrentUser.UserName : "")" @(isrelated ? " disabled" : "") />
                                                    <input type="hidden" name="@(inputName)" data-name="@attr.Name.ToLower()" data-type="lookup" data-controltype="lookup" data-value="" data-lookup="@attr.ReferencedEntityId" data-entityname="@attr.EntityName" value="@(!isrelated ? app.CurrentUser.SystemUserId.ToString() : "")" />
                                                }*@
                                            else if (attr.TypeIsOwner())
                                            {
                                                <input type="text" data-isrelated="@isrelated" class="form-control input-sm  @(isrelated ? "" : "lookup")  owner" data-isedit="true" name="@(inputName + "_text")" data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-lookup="@attr.ReferencedEntityId" data-entityname="@attr.EntityName" value="@(!isrelated ? app.CurrentUser.UserName : "")" @(isrelated ? " disabled" : "") />
                                                <input type="hidden" data-isrelated="@isrelated" name="@(inputName)" data-name="@attr.Name.ToLower()" data-type="lookup" data-controltype="lookup" data-value="" data-lookup="@attr.ReferencedEntityId" data-entityname="@attr.EntityName" value="@(!isrelated ? app.CurrentUser.SystemUserId.ToString() : "")" />
                                            }
                                            else if (attr.TypeIsPickList() || attr.TypeIsBit() || attr.TypeIsState() || attr.TypeIsStatus())
                                            {
                                                if (isrelated)
                                                {
                                                    <input type="text" data-isrelated="@isrelated" class="form-control input-sm" name="@(inputName)" data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-entityname="@attr.EntityName" disabled />
                                                }
                                                else
                                                {
                                                    var itemStr = (attr.TypeIsPickList() || attr.TypeIsStatus()) ? attr.OptionSet.Items.SerializeToJson() : attr.PickLists.SerializeToJson();
                                                    <input type="text" data-isrelated="@isrelated" class="form-control input-sm @attr.AttributeTypeName" data-isedit="true" name="@(inputName)" data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-entityname="@attr.EntityName" data-items="@(Html.UrlEncoder.Encode(itemStr))" />
                                                }
                                            }
                                            else
                                            {
                                                <input type="text" data-isrelated="@isrelated" class="form-control isvalidata normal-input @(isrelated ? "" : @attr.AttributeTypeName) input-sm " name="@(inputName)" data-name="@attr.Name.ToLower()" data-isedit="true" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-format="@attr.DataFormat" data-dataformat="@attr.DataFormat" data-entityname="@attr.EntityName" @(isrelated ? " disabled" : "") />
                                            }
                                        }
                                    </td>
                                }
                            </tr>
                        }
                        @{
                            var primaryKey = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && n.TypeIsPrimaryKey());
                            var primaryField = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && n.IsPrimaryField == true);
                            int rowNum = 0;
                        }
                        @foreach (var item in Model.Items)
                        {
                            rowNum++;
                            var lines = (item as IDictionary<string, object>).ToList();
                            var id = lines.Find(n => n.Key.IsCaseInsensitiveEqual(primaryKey.Name)).Value;
                            <tr data-dbclick="Xms.Web.OpenWindow(ORG_SERVERURL+'/entity/create?entityid=@mainEntity.EntityId&recordid=@id')" data-isinit="true">
                                @if (Model.IsEditable)
                                {
                                    <td>
                                        <input type="checkbox" name="recordid" value="@id" data-primarykey="@primaryKey.Name" />
                                        <input type="hidden" name="rownumber" value="@rowNum" />
                                    </td>
                                    <td class="row-num">@rowNum</td>
                                }
                                @if (Model.IsEditable && Model.RelationShipName.IsNotEmpty())// && Model.ReferencedRecordId.HasValue)
                                {
                                    <td data-operation="true">
                                        @*<div class="btn-group">
                                                <button type="button" class="btn btn-link btn-xs" name="editRowBtn">
                                                    <span class="glyphicon glyphicon-edit"></span>
                                                </button>
                                            </div>*@
                                        @*<div class="btn-group">
                                                <button type="button" class="btn btn-link btn-xs" name="saveRowBtn">
                                                    <span class="glyphicon glyphicon-saved"></span>
                                                </button>
                                            </div>*@
                                        <div class="btn-group">
                                            <button type="button" class="btn btn-link btn-xs" name="removeRowBtn"><span class="glyphicon glyphicon-remove"></span></button>
                                        </div>
                                    </td>
                                }
                                @foreach (var cell in Model.Grid.Rows[0].Cells)
                                {
                                    var columnName = cell.Name.ToLower();
                                    var isrelated = columnName.IndexOf(".") > 0;
                                    var attrName = isrelated ? columnName.Split('.')[1] : columnName;
                                    Xms.Schema.Domain.Attribute attr = null;
                                    if (isrelated)
                                    {
                                        attr = Model.AttributeList.Find(n => n.EntityName.IsCaseInsensitiveEqual(cell.EntityName) && n.Name.IsCaseInsensitiveEqual(attrName));
                                    }
                                    else
                                    {
                                        attr = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && n.Name.IsCaseInsensitiveEqual(attrName));
                                    }
                                    var inputName = (Model.RelationShipName.IfEmpty(attr.EntityName) + "_" + attr.Name).ToLower();
                                    var required = attr.IsRequired ? "required" : "";
                                    if (attr.TypeIsPrimaryKey() || attr.TypeIsLookUp() || attr.TypeIsOwner())
                                    {
                                        columnName = attr.TypeIsPrimaryKey() ? primaryField.Name : columnName += "Name";
                                        var value = lines.Find(n => n.Key.IsCaseInsensitiveEqual(columnName)).Value;
                                        var recordid = lines.Find(n => n.Key.IsCaseInsensitiveEqual(cell.Name)).Value;
                                        <td data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-isrequired="@required" data-entityname="@attr.EntityName" data-localizedname="@attr.LocalizedName">
                                            @if (!Model.IsEditable)
                                            {
                                                <a href="@("/"+app.OrganizationUniqueName)/entity/edit?entityid=@attr.ReferencedEntityId&recordid=@recordid" target="_blank">@value</a>
                                            }
                                            else
                                            {
                                                <input type="text" class="form-control input-sm  @(isrelated ? "" : "lookup") typeahead" name="@(inputName + "_text")" data-isrelated="@isrelated" data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-value="@recordid" value="@value" data-lookup="@attr.ReferencedEntityId" data-entityname="@attr.EntityName" @(isrelated ? "disabled" : "") />
                                                <input type="hidden" name="@(inputName)" data-isedit="true" data-name="@attr.Name.ToLower()" data-type="lookup" data-controltype="lookup" value="@recordid" data-lookup="@attr.ReferencedEntityId" data-isrelated="@isrelated" data-entityname="@attr.EntityName">
                                            }
                                        </td>
                                    }
                                    else if (attr.TypeIsPickList() || attr.TypeIsState() || attr.TypeIsStatus())
                                    {
                                        columnName += "Name";
                                        var value = lines.Find(n => n.Key.IsCaseInsensitiveEqual(columnName)).Value;
                                        var valuenum = lines.Find(n => n.Key.IsCaseInsensitiveEqual(cell.Name.ToLower())).Value;

                                        <td data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-isrequired="@required" data-entityname="@attr.EntityName" data-localizedname="@attr.LocalizedName">
                                            @if (isrelated)
                                            {
                                                <input type="text" data-isrelated="@isrelated" class="form-control input-sm" name="@(inputName)" data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-entityname="@attr.EntityName" value="@valuenum" disabled />
                                            }
                                            else
                                            {
                                                var itemStr = (attr.TypeIsPickList() || attr.TypeIsStatus()) ? attr.OptionSet.Items.SerializeToJson() : attr.PickLists.SerializeToJson();
                                                <input type="text" class="form-control input-sm @attr.AttributeTypeName" data-isedit="true" name="@(inputName)" data-name="@attr.Name.ToLower()" data-isrelated="@isrelated" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-entityname="@attr.EntityName" value="@valuenum" data-items="@(Html.UrlEncoder.Encode(itemStr))" />
                                            }
                                        </td>

                                    }
                                    else if (attr.TypeIsBit())
                                    {
                                        columnName += "Name";
                                        var value = lines.Find(n => n.Key.IsCaseInsensitiveEqual(columnName)).Value;
                                        String valuenum = lines.Find(n => n.Key.IsCaseInsensitiveEqual(cell.Name.ToLower())).Value + "";

                                        <td data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-isrequired="@required" data-entityname="@attr.EntityName" data-localizedname="@attr.LocalizedName">
                                            @if (isrelated)
                                            {
                                                if (valuenum == "True")
                                                {
                                                    valuenum = "是";
                                                }
                                                else if (valuenum == "False")
                                                {
                                                    valuenum = "否";
                                                }
                                                else
                                                {
                                                    valuenum = "";
                                                }
                                                <input type="text" data-isrelated="@isrelated" class="form-control input-sm" name="@(inputName)" data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-entityname="@attr.EntityName" value="@valuenum" disabled />
                                            }
                                            else
                                            {
                                                var itemStr = (attr.TypeIsPickList() || attr.TypeIsStatus()) ? attr.OptionSet.Items.SerializeToJson() : attr.PickLists.SerializeToJson();
                                                if (valuenum == "True")
                                                {
                                                    valuenum = "1";
                                                }
                                                else if (valuenum == "False")
                                                {
                                                    valuenum = "0";
                                                }
                                                else
                                                {
                                                    valuenum = "";
                                                }
                                                <input type="text" data-isrelated="@isrelated" class="form-control input-sm @attr.AttributeTypeName" data-isedit="true" name="@(inputName)" data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-entityname="@attr.EntityName" data-value="@valuenum" value="@valuenum" data-items="@(Html.UrlEncoder.Encode(itemStr))" />
                                            }
                                        </td>

                                    }
                                    else if (attr.TypeIsDateTime())
                                    {
                                        var value = lines.Find(n => n.Key.IsCaseInsensitiveEqual(columnName)).Value;
                                        value = string.Format("{0:G}", value);

                                        <td data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-isrequired="@required" data-entityname="@attr.EntityName" data-localizedname="@attr.LocalizedName"><input type="text" class="form-control isvalidata input-sm datepicker datetime" data-isedit="true" name="@(inputName)" value="@value" data-dataformat="@attr.DataFormat" data-format="@attr.DataFormat" data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-entityname="@attr.EntityName" @(isrelated || attr.Name.IsCaseInsensitiveEqual("createdon") || attr.Name.IsCaseInsensitiveEqual("modifiedon") ? " disabled" : "") /></td>

                                    }
                                    else
                                    {
                                        var value = lines.Find(n => n.Key.IsCaseInsensitiveEqual(columnName)).Value;
                                        var precision = "";
                                        if (value != null && (attr.TypeIsDecimal()
                                                        || attr.TypeIsFloat()))
                                        {
                                            value = string.Format("{0:N" + attr.Precision + "}", value);
                                            precision = attr.Precision.ToString();
                                        }
                                        else if (value != null && attr.TypeIsMoney())
                                        {
                                            value = string.Format("{0:N" + attr.Precision + "}", value);
                                            precision = attr.Precision.ToString();
                                        }
                                        else if (value != null && attr.TypeIsDateTime())
                                        {
                                            value = string.Format("{0:G}", value);
                                        }
                                        //else if (attr.IsPrimaryField)
                                        //{
                                        //    value = value;//string.Format("<a href=\"/entity/create?entityid={0}&recordid={1}\" target=\"_blank\">{2}</a>", mainEntity.EntityId, id, value);
                                        //}
                                        else if (attr.TypeIsNvarchar())
                                        {
                                            if (attr.DataFormat == "url" && value != null && value.ToString().IsNotEmpty())
                                            {
                                                var link = string.Format("<a href=\"{0}\" title=\"新窗口打开\" target=\"_blank\"><span class=\"glyphicon glyphicon-share-alt\"></span></a>", value);
                                                <td data-name="@attr.Name.ToLower()" class="datatype-link" data-attributetypename="@attr.AttributeTypeName">
                                                    @link
                                                    <span class="glyphicon glyphicon-edit" onclick="$(this).hide();$(this).prev().hide();$(this).next().removeClass('hide').focus()"></span>
                                                    <input type="text" data-isrelated="@isrelated" value="@value" onchange="$(this).addClass('hide');$(this).prev().show();$(this).prev().prev().show().attr('href',$(this).val());$(this).next().val($(this).val()).trigger('change');" onblur="$(this).addClass('hide');$(this).prev().show();$(this).prev().prev().show().attr('href',$(this).val());$(this).next().val($(this).val());" class="form-control hide" />
                                                    <input type="hidden" data-isrelated="@isrelated" class="form-control normal-input isvalidata input-sm @attr.AttributeTypeName" data-dataformat="@attr.DataFormat" name="@(inputName)" data-name="@attr.Name.ToLower()" data-isedit="true" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-entityname="@attr.EntityName" @(isrelated ? " disabled" : "") value="@value" />
                                                </td>
                                                continue;
                                            }
                                        }

                                        <td data-name="@attr.Name.ToLower()" data-type="@attr.AttributeTypeName" data-isrequired="@required" data-entityname="@attr.EntityName" data-localizedname="@attr.LocalizedName"><input type="text" class="form-control normal-input isvalidata input-sm @attr.AttributeTypeName" data-dataformat="@attr.DataFormat" data-isrelated="@isrelated" name="@(inputName)" data-name="@attr.Name.ToLower()" data-precision="@precision" data-isedit="true" data-type="@attr.AttributeTypeName" data-controltype="@attr.AttributeTypeName" data-entityname="@attr.EntityName" @(isrelated ? " disabled" : "") value="@value" /></td>

                                    }
                                }
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
            @if (Model.PagingEnabled)
            {
                <div class="panel-footer@(Model.TotalItems > 0 ? "" : " hide")" style="padding:3px; margin-bottom:55px;">
                    <div class="row">
                        <div class="col-sm-4">
                            @(app.T["pagination_label"].Replace("{page}", Model.Page.ToString()).Replace("{totalpages}", Model.TotalPages.ToString()).Replace("{totalitems}", Model.TotalItems.ToString()))
                        </div>
                        <div id="page-selection" class="col-sm-8" data-total="@Model.TotalPages" data-page="@Model.Page"></div>
                    </div>
                </div>
            }
        </div>
    </div>
</div>

<script src="/content/js/jquery.bootpag.min.js?v=@app.PlatformSettings.VersionNumber"></script>
<script src="/content/js/jquery.form.js?v=@app.PlatformSettings.VersionNumber"></script>
<script src="~/content/js/fetch.js?v=@app.PlatformSettings.VersionNumber"></script>
@foreach (var item in jsLibs)
{
    <script src="@item"></script>
}
@if (resources.Count > 0)
{
    <script src="@("/"+app.OrganizationUniqueName)/api/webresource?ids=@(string.Join(",", resources))"></script>
}
@*@{await Html.RenderPartialAsync("FetchLabel"); }*@
<script>
    var pageRenderGridViewInfo = {
        sectionid: '#@gridid',
        gridid: '@Model.GridId',
        iseditable:true,
        pageUrl: $("#@gridid .datatable").attr('data-pageurl'),
        queryid: '@Model.QueryViewId',
        entityid: '@Model.EntityId',
        entityname: '@mainEntity.Name.ToLower()',
        entityloclaizedname: '@mainEntity.LocalizedName',
        filters: @Html.Raw(Model.Filter.SerializeToJson()),
        sortby: '@Model.SortBy',
        sortdir: '@Model.SortDirection',
        q: '@Model.Q',
        defaultEmptyRows: '@Model.DefaultEmptyRows',//初始化行数
        pagingEnabled: @(Model.PagingEnabled ? "true":"false"),
        qfield: '@Model.QField',
        page: @Model.Page,
        pagesize: @Model.PageSize,
        relationshipmeta: @Html.Raw(Model.RelationShipMeta != null ? Model.RelationShipMeta.SerializeToJson() : "null"),
        relationshipname: '@Model.RelationShipName.IfEmpty("").ToLower()',
        referencedrecordid: '@Model.ReferencedRecordId',
        referencingattributename: '@(Model.RelationShipMeta != null? Model.RelationShipMeta.ReferencingAttributeName.IfEmpty("").ToLower():"")',
        //gridconfig:[{"name":"productid", "editable":true},{"name":"quantity", "editable":true, "onchange":{"func":"update","target":"amount"}},{"name":"price", "editable":true, "bind":"model.price", "onchange":{"func":"update","target":"amount"}},{"name":"discountamount", "editable":true, "onchange":{"func":"update","target":"amount"}},{"name":"amount", "editable":false, "exp":"row.price*row.quantity-row.discountamount"}],
        records: [],
        nameprefix: '@Model.RelationShipName.IfEmpty(mainEntity.Name).ToLower()' + '_',
        editrowmodel: null,
        createmode: Xms.Page && Xms.Page.PageContext && Xms.Page.PageContext.RecordId == null ? 'local' : 'server'//local or server
    }
</script>
<script src="/content/js/pages/entity.rendergridview.js?v=@app.PlatformSettings.VersionNumber"></script>
<script>

        function formSaveSubGrid(){
            var check = checkSubGridData();
            //console.log('checkxxxxxxxxxxxxxxxxx',check)
            if(!check)return false;
            var flag = true;
            for(var key in GridViewModel){
                var sfl = true;
                if(GridViewModel.hasOwnProperty(key)){
                    sfl = GridViewModel[key].savetable();
                }
                if(sfl==false){
                    flag = false;
                    //break;
                }
            }
            console.log('flag',flag);
            if(flag){
                var res = [];
                $('input[name="resdata"]').each(function(){
                    if(!$(this).val()||$(this).val()=="")return true;
                    var temp = JSON.parse(decodeURIComponent($(this).val()));
                    res = res.concat(temp);
                });
                $('input[name="child"]').val('').val(encodeURIComponent(JSON.stringify(res)));
                console.log('提交单据体的数据',res)
                //console.log('提交单据体的数据2',JSON.parse(decodeURIComponent(resultValue)));
                dirtyChecker.isDirty = true;
            }
            return flag;
        }
</script>